package 线程同步.死锁;

public class ADeadlock {
    public static void main(String[] args) {
        cf cf = new cf();
        Thread thread = new Thread(cf, "小米");
        Thread thread1 = new Thread(cf, "小花");
        System.out.println(thread.getName()+"-->"+thread.getState());
        thread.start();
        System.out.println(thread.getName()+"-->"+thread.getState());
        thread1.start();
        while (thread.getState().equals(Thread.State.TERMINATED)){
            System.out.println(thread.getName()+"-->"+thread.getState());
        }


    }
}

//资源a
class a {
    public void A() {
        System.out.println(Thread.currentThread().getName() + "A线程-->吃饭");
    }
}

//资源b
class b {
    public void B() {
        System.out.println(Thread.currentThread().getName() + "B线程-->吃菜");
    }
}

class cf implements Runnable {
    a a = new a();
    b b = new b();
    private static int i = 0;//控制线程的执行顺序

    @Override
    public void run() {
        cfl();
    }

    //吃饭的方法
    public void cfl() {
        if (i == 0) {
            i = 1;
            synchronized (a) {

                a.A();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    b.B();
                }
            }
        } else {
            synchronized (b) {

                b.B();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a) {
                    a.A();
                }
            }
        }

    }

}